//实现异步日志缓冲区
#ifndef __M_BUF_H__
#define __M_BUF_H__
#include<util.hpp>
#include<vector>
#include<cassert>
namespace log
{
    #define DEFAULT_BUFFER_SIZE (1*1024*1024)
    #define THREASHOL_BUFFER_SIZE (8*1024*1024)//阈值
    #define INCREMENT_BUFFER_SIZE (1*1024*1024)//线性增长的大小


    class Buffer
    {
        public: 
            Buffer(): _buffer(DEFAULT_BUFFER_SIZE),_writer_idx(0),_reader_idx(0){}

            void push(const char *data,size_t len)
            {
              
                ensureEnoughSize(len);
         
                std::copy(data,data+len,&_buffer[_writer_idx]);

                moveWriter(len);
            }
            size_t writeAbleSize()
            {
                return (_buffer.size()-_writer_idx);
            }

            const char* begin()
            {
                return &_buffer[_reader_idx];
            }
            size_t reabAbleSize()
            {
                return (_writer_idx-_reader_idx);
            }
            void moveReader(size_t len)
            {
                assert(len<=reabAbleSize());
                _reader_idx+=len;
            }
          
            void reset()
            {
                _writer_idx=0;
                _reader_idx=0;
            }
            //对Buffer实现交换操作
            void swap(Buffer &buffer)
            {
                _buffer.swap(buffer._buffer);
                std::swap(_reader_idx,buffer._reader_idx);
                std::swap(_writer_idx,buffer._writer_idx);
            }
            //判断缓冲区是否为空
            bool empty()
            {
                return (_reader_idx==_writer_idx);
            }
        private:
            //对空间进行扩容
            void ensureEnoughSize(size_t len)
            {
                if(len<writeAbleSize())
                {
                    return;//不需要扩容
                }
                size_t new_size=0;
                if(_buffer.size()<THREASHOL_BUFFER_SIZE)
                {
                    new_size=_buffer.size()*2;//小于阈值翻倍增长
                }
                else
                {
                    new_size=_buffer.size()+INCREMENT_BUFFER_SIZE;//否则线性增长
                }
                _buffer.resize(new_size);
            }
            //对读写指针进行向后偏移操作
            void moveWriter(size_t len)
            {
                assert(len+_writer_idx<=_buffer.size());
                _writer_idx+=len;
            }
        private:
            std::vector<char> _buffer;
            size_t _reader_idx;
            size_t _writer_idx;
    };
}

#endif